﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web;

namespace TuyennvLibrary.Notify.Winphone
{
    public class WinphoneNotify
    {
        private string mResponse = string.Empty;
        private Dictionary<string, object> Params = new Dictionary<string, object>();
        public string Uri { get; set; }
        public string Title { get; set; }
        public string Message { get; set; }
        public string PageXaml { get; set; }
        public string Response { get { return mResponse; } }

        public WinphoneNotify()
        {
            Params = new Dictionary<string, object>();

        }
        public void AddParam(string key, object value)
        {
            Params.Add(key, value);
        }
        private string ToParams()
        {
            string result = string.Empty;
            int i = 0;
            foreach (var item in Params)
            {
                result += string.Format("{0}={1}{2}", item.Key, item.Value, (i < Params.Count - 1) ? "&amp;" : "");
                i++;
            }

            return result;
        }
        public static string HtmlEncode(string text)
        {
            char[] chars = HttpUtility.HtmlEncode(text).ToCharArray();
            StringBuilder result = new StringBuilder(text.Length + (int)(text.Length * 0.1));

            foreach (char c in chars)
            {
                int value = Convert.ToInt32(c);
                if (value > 127)
                    result.AppendFormat("&#{0};", value);
                else
                    result.Append(c);
            }

            return result.ToString();
        }
        public WinphoneNotifyResponse Push()
        {
            WinphoneNotifyResponse mResponse = new WinphoneNotifyResponse();
            try
            {
                string subscriptionUri = Uri;


                HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri);

                // Create an HTTPWebRequest that posts the toast notification to the Microsoft Push Notification Service.
                // HTTP POST is the only method allowed to send the notification.
                sendNotificationRequest.Method = "POST";

                // The optional custom header X-MessageID uniquely identifies a notification message. 
                // If it is present, the same value is returned in the notification response. It must be a string that contains a UUID.
                // sendNotificationRequest.Headers.Add("X-MessageID", "<UUID>");

                // Create the toast message.
                string param = ToParams();
                string toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<wp:Notification xmlns:wp=\"WPNotification\">" +
                   "<wp:Toast>" +
                        "<wp:Text1>" + HtmlEncode(Title) + "</wp:Text1>" +
                        "<wp:Text2>" + HtmlEncode(Message) + "</wp:Text2>" +
                        "<wp:Param>" + string.Format("/{0}{1}", PageXaml, (param != "") ? "?" + param : "") + "</wp:Param>" +
                   "</wp:Toast> " +
                "</wp:Notification>";

                // Set the notification payload to send.
                byte[] notificationMessage = Encoding.Default.GetBytes(toastMessage);

                // Set the web request content length.
                sendNotificationRequest.ContentLength = notificationMessage.Length;
                sendNotificationRequest.ContentType = "text/xml";
                sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "toast");
                sendNotificationRequest.Headers.Add("X-NotificationClass", "2");


                using (Stream requestStream = sendNotificationRequest.GetRequestStream())
                {
                    requestStream.Write(notificationMessage, 0, notificationMessage.Length);
                }

                // Send the notification and get the response.
                HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();
                string notificationStatus = response.Headers["X-NotificationStatus"];
                string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
                string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];

                // Display the response from the Microsoft Push Notification Service.  
                // Normally, error handling code would be here. In the real world, because data connections are not always available,
                // notifictions may need to be throttled back if the device cannot be reached.
                mResponse.NotifyStatus = notificationStatus;
                mResponse.ConnectionStatus = deviceConnectionStatus;
                mResponse.ChannelStatus = notificationChannelStatus;
                mResponse.CheckResponse();
                return mResponse;
            }
            catch (Exception ex)
            {
                mResponse.Fail(ex.Message);
                return mResponse;
            }
        }
    }
}
